﻿namespace Xms.Abp.Components;

public partial class ConditionSection
{
    [Parameter] public List<ConditionField> Fields { get; set; }
    private ConditionModel _value;
    [Parameter]
    public ConditionModel Value
    {
        get => _value;
        set
        {
            if (_value == value) return;
            _value = value;
            if (ValueChanged.HasDelegate)
            {
                ValueChanged.InvokeAsync(value);
            }
            if (Fields != null && value.Type == ConditionType.Condition)
            {
                _CurrentField = Fields.FirstOrDefault(r => r.Field == value.Condition.Field);
            }
            StateHasChanged();
        }
    }
    [Parameter] public EventCallback<ConditionModel> ValueChanged { get; set; }
    [Parameter] public bool ReadOnly { get; set; }

    private ConditionField _CurrentField;

    protected override async Task OnInitializedAsync()
    {
        if (_CurrentField == null && Value.Type == ConditionType.Condition)
        {
            _CurrentField = Fields.FirstOrDefault(r => r.Field == Value.Condition.Field);
        }
        await base.OnInitializedAsync();
    }

    private void OnFieldChange(ConditionField field)
    {
        Value.Condition.Field = field.Field;
        Value.Condition.CompareDataType = field.CompareDataType;
        _CurrentField = field;
    }

    private void OnBoolChange(bool value)
    {
        OnStringChange(value.ToString());
    }

    private void OnLongChange(long value)
    {
        OnStringChange(value.ToString());
    }

    private void OnDecimalChange(decimal value)
    {
        OnStringChange(value.ToString());
    }

    private void OnEnumChange(NameValue<int> value)
    {
        OnStringChange(value.Value.ToString());
    }

    private void OnDateTimeChange(DateTimeChangedEventArgs args)
    {
        OnStringChange(args.DateString);
    }

    private void OnDataDictionaryChange(NameValue<Guid?> value)
    {
        OnStringChange(value.Value?.ToString() ?? "");
    }

    private void OnStringChange(string value)
    {
        Value.Condition.Value = value;
    }

    private void OnCompareTypeChange(CompareType compareType)
    {
        if (compareType == CompareType.HasValue || compareType == CompareType.NotHasValue || compareType == CompareType.Empty || compareType == CompareType.NotEmpty)
        {
            OnStringChange("");
        }
        Value.Condition.CompareType = compareType;
    }
}
